package com.gxg.web.Base;

import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by guxiaoguang on 2018/5/11.
 */

import com.alibaba.fastjson.JSONObject;
import com.gxg.common.exception.RunEx;
import com.gxg.common.logger.Logger;
import com.gxg.common.mobile.CheckMobile;
import com.gxg.common.redis.JedisClient;
import com.gxg.common.validate.Validators;
import com.gxg.config.code.RCode;
import com.gxg.config.code.UserTokenConstants;

/**
 * 通用Controller
 *
 * @author hewei
 */
public class BaseController {

    /**
     * 验证请求参数
     *
     * @param result
     * @param request
     * @param obj
     */
    public static void verify(BindingResult result, HttpServletRequest request, Object obj) {
        Logger.reqLogger(request, obj);
        // 验证上送字段是否合法
        if (result.hasErrors()) {
            String field = result.getFieldError().getField();
            String defaultMessage = result.getFieldError().getDefaultMessage();
            Logger.info("参数返回：" + defaultMessage);
            throw new RunEx(RCode.REQUEST_ERR, "[" + field + "]" + defaultMessage);
        }
    }

    /**
     * TOKEN校验 常用获取userId
     *
     * @param accessToken
     * @param jedisClient
     * @return
     */
    public static String verify(HttpServletRequest request, String accessToken, JedisClient jedisClient) {
        return verify(request, accessToken, jedisClient, "UserToken", "userId");

    }

    /**
     * 验证请求参数，并校验TOKEN 常用获取userId
     *
     * @param result
     * @param request
     * @param obj
     * @param accessToken
     * @param jedisClient
     */
    public static String verify(BindingResult result, HttpServletRequest request, Object obj, String accessToken,
                                JedisClient jedisClient) {
        verify(result, request, obj);
        return verify(request, accessToken, jedisClient, "UserToken", "userId");
    }

    /**
     * 验证请求参数，并校验TOKEN
     *
     * @param result
     * @param request
     * @param obj
     * @param accessToken
     * @param jedisClient
     * @param prefix      redis key的前缀
     * @param key         需要获取TOKEN中的key
     */
    public static String verify(BindingResult result, HttpServletRequest request, Object obj, String accessToken,
                                JedisClient jedisClient, String prefix, String key) {
        verify(result, request, obj);
        return verify(request, accessToken, jedisClient, prefix, key);
    }

    /**
     * TOKEN校验
     *
     * @param accessToken
     * @param jedisClient
     * @param prefix      redis key的前缀
     * @param key         需要获取TOKEN中的key
     * @return
     */
    public static String verify(HttpServletRequest request, String accessToken, JedisClient jedisClient, String prefix,
                                String key) {
        Logger.reqLogger(request, accessToken);
        if (Validators.isBlank(accessToken)) {
            throw new RunEx(RCode.REQUEST_ERR, "令牌不能为空！");// 无权访问
        }
        if (accessToken.length() > 100) {
            throw new RunEx(RCode.REQUEST_ERR, "令牌长度不能超出100！");// 无权访问
        }
        boolean isMo = CheckMobile.check(request.getHeader("user-agent").toString().toLowerCase());
        String terminal_type = UserTokenConstants.TERMINAL_TYPE_WEB;
        if (isMo) {
            terminal_type = UserTokenConstants.TERMINAL_TYPE_WECAHT;
        }
        String resKey = prefix + "_" + terminal_type + "_" + accessToken;
        Logger.info("TOKEN校验全程为：" + resKey);
        String jsonstr = null;
        // 如果是ddp的TOKEN则转成yxcatId
        if (key.toLowerCase().equals(UserTokenConstants.USERID.toLowerCase())) {
            if (resKey.contains("DDP_")) {
                Logger.info("由于平台融合原因TOKEN兼容处理，当前TOKEN转为了yxcatID");
                key = UserTokenConstants.YXCATID;
            }
        }
        jsonstr = jedisClient.get(resKey);
        JSONObject jsonObject = JSONObject.parseObject(jsonstr);
        try {
            return jsonObject.getString(key);
        } catch (Exception e) {
            throw new RunEx(RCode.PERMISSION_ERR, "not authorized to access");// 无权访问
        }

    }

}
